package com.project.lk.nurseapp.doctor.model;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.project.lk.nurseapp.base.BaseApi;
import com.project.lk.nurseapp.base.PostBaseModel;
import com.project.lk.nurseapp.login.model.UserBean;
import com.project.lk.nurseapp.utils.JsonUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.FormBody;

/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */

public class DoctorModel extends PostBaseModel {



    int page=1;
    public void postLoadJson(String url,String sessionId){
        Random random = new Random();
        int nextInt = random.nextInt();
        FormBody.Builder builder = new FormBody.Builder();
        long currentTimeMillis = System.currentTimeMillis();
        builder.add("signature",postSignToken(currentTimeMillis+"",nextInt+""))
                .add("timestamp",currentTimeMillis+"")
                .add("nonce",nextInt+"")
                .add("sessionId",sessionId)
                .add("rows","10")
                .add("page",page+"");
        getJsonData(url,builder.build());

    }

    @Override
    public List analyzeJson(String json, String url) {
        Log.e("MLOG",url+json);
        try {
            JSONObject object=new JSONObject(json);
            JSONArray array = object.getJSONArray("rows");
            List<DoctorItemBean> list = (List<DoctorItemBean>) JsonUtils.getJsonUtils()
                    .toObject(new TypeToken<List<DoctorItemBean>>(){}.getType(),array.toString());
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("MLOG",e.getMessage());
            showFail();
        }
        return null;
    }

    public void noMore(){
        bridge.bridge(BaseApi.noMore,null);
    }

    public void loadMore(){
        page++;
    }

    public void refresh(){
        page=1;
    }

    public void showSuccess(){

        bridge.bridge(BaseApi.show_list,null);
    }
    public void showFail(){

        bridge.bridge(BaseApi.fail,null);
    }
    List<DoctorItemBean> mList=new ArrayList<>();

    public List<DoctorItemBean> getmList() {
        return mList;
    }

    @Override
    public void postSuccessOnMainThread(List list, String url) {
        if (list!=null){
            if (page == 1) {
                mList.clear();
            }
            if (list.size() == 0) {
                bridge.bridge(BaseApi.noMore,list);
                return;
            }
            mList.addAll(list);
            bridge.bridge(BaseApi.show_list,mList);
        }else {
            showFail();
        }
    }
    @Override
    public void postFailedOnMainThread(String url) {
        showFail();
    }
}
